package org.jflame.context.mq;

import org.jflame.context.cache.CacheWrapper;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.amqp.core.MessageProperties;

/**
 * 实现重复消息判断的消息接收监听器父类.
 * <p>
 * 通过缓存消息id,判断消息是否重复.
 * 
 * @author charles.zhang
 */
public abstract class AbstractRabbitTextMessageListener extends AbstractRabbitMessageListener {

    protected boolean enableLogInfoLevel = false;

    public AbstractRabbitTextMessageListener(CacheWrapper<String,Integer> cache) {
        super(cache);
    }

    /**
     * 消息处理业务逻辑
     * 
     * @param message
     * @param messageId
     * @param messageProperties
     * @return MqAction
     * @throws Exception
     */
    protected MqAckAction handleMessage(final byte[] message, MessageProperties messageProperties) throws Exception {
        if (message != null) {
            String msgText = new String(message,
                    messageProperties.getContentEncoding() != null
                            ? Charset.forName(messageProperties.getContentEncoding())
                            : StandardCharsets.UTF_8);
            if (enableLogInfoLevel) {
                logger.info("receive mq msg, id:{}, body: {}", messageProperties.getMessageId(), msgText);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("receive mq msg,id:{},body: {}", messageProperties.getMessageId(), msgText);
                }
            }

            return handleTextMessage(msgText, messageProperties);
        }
        return MqAckAction.ACCEPT;
    }

    protected abstract MqAckAction handleTextMessage(final String message, MessageProperties messageProperties)
            throws Exception;
}
